import { WebSocketServer } from "ws";
import mockjs from "mockjs";

// 随机数据
const Random = mockjs.Random;
Random.date();
Random.city();
Random.id();

function getRandomData() {
  return mockjs.mock({
    "list|5-25": [
      {
        id: "@id",
        date: "@date",
        address: "@city",
        "num|100-9999": 100,
      },
    ],
  });
}

function sendData(ws) {
  const data = getRandomData();
  ws.send(JSON.stringify(data.list));

  const timeId = setInterval(() => {
    const data = getRandomData();
    ws.send(JSON.stringify(data.list));
  }, 5000);

  ws.once("close", () => {
    clearInterval(timeId);
  });
}

// web socket
const wss = new WebSocketServer({
  port: 3001,
});

wss.on("connection", (ws) => {
  // 给客户端发送消息
  sendData(ws);
  // 接受客户端消息（心跳检测）
  ws.on("message", (data) => {
    if (data.toString() === "ping") {
      ws.send("pong");
    }
  });
});
